#include <cstdio>
#include <cstring>
#include "ServerCommon.h"
#include "UserService.h"


int UserService::getConnection()
{
	char mess[USER_MESS_LEN];
	conn.connectToService(USER_IP, USER_PORT);
	sprintf(mess, "request service");
	conn.TcpSend(mess, USER_MESS_LEN);
	conn.TcpRecv(mess, USER_MESS_LEN);
	if (!strncmp(mess, "OK", strlen("OK")))
		return 1;
	else
		return 0;
}

int UserService::sendApp(const char *path, const char *name)
{
	char mess[USER_MESS_LEN];
	sprintf(mess, "%s", name);
	conn.TcpSend(mess, USER_MESS_LEN);
	return sendData(path, name);
}

int UserService::sendInput(const char *path, const char *name)
{
	char mess[USER_MESS_LEN];
	sprintf(mess, "%s", name);
	conn.TcpSend(mess, USER_MESS_LEN);
	return sendData(path, name);
}

int UserService::sendSched(const char *path, const char *name)
{
	char mess[USER_MESS_LEN];
	sprintf(mess, "%s", name);
	conn.TcpSend(mess, USER_MESS_LEN);
	return sendData(path, name);
}

int UserService::sendData(const char *path, const char *name)
{
	char mess[USER_MESS_LEN];
	char *buf;
	FILE *app = fopen(path, "r");
	int size;
	int i = 0;
	fseek(app, 0L, SEEK_END);
	size = ftell(app);
	fseek(app, 0L, SEEK_SET);
	buf = new char[size];
	sprintf(mess, "data %d", size);
	conn.TcpSend(mess, USER_MESS_LEN);
	fread(buf, size, 1, app);
	while (i < size) {
		if (i + USER_MESS_LEN >= size) {
			for (;i<size;i++)
				mess[i%USER_MESS_LEN] = buf[i];
		} else {
			memcpy(mess, buf+i, USER_MESS_LEN);
			i += USER_MESS_LEN;
		}
		conn.TcpSend(mess, USER_MESS_LEN);
	}
	conn.TcpRecv(mess, USER_MESS_LEN);
	if (!strncmp(mess, "OK", strlen("OK")))
		return 1;
	else
		return 0;
}

int UserService::sendPara(const double CGRatio, const int minNodes)
{
	char mess[USER_MESS_LEN];
	sprintf(mess, "%lf %d", CGRatio, minNodes);
	conn.TcpSend(mess, USER_MESS_LEN);
	conn.TcpRecv(mess, USER_MESS_LEN);
	if (!strncmp(mess, "OK", strlen("OK")))
		return 1;
	else
		return 0;
}

int UserService::recvResults(char **buf)
{
	char mess[USER_MESS_LEN];
	int nodes;
	int data_len;
	int i, j;
	conn.TcpRecv(mess, USER_MESS_LEN);
	sscanf(mess, "total node %d", &nodes);
	for (i=0;i<nodes;i++) {
		conn.TcpRecv(mess, USER_MESS_LEN);
		sscanf(mess, "data %d", &data_len);
		j = 0;
		while (j < data_len) {
			conn.TcpRecv(mess, USER_MESS_LEN);
			if (j + USER_MESS_LEN >= data_len) {
				for (;j<data_len;j++)
					buf[i][j] = mess[j%USER_MESS_LEN];
			} else {
				memcpy(buf[i]+j, mess, USER_MESS_LEN);
				j += USER_MESS_LEN;
			}
		}
	}
	sprintf(mess, "OK");
	conn.TcpSend(mess, USER_MESS_LEN);
	return 0;
}
